package com.tdd.api.server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tdd.api.server.domain.result.wx.service.PushReturn;
import com.tdd.api.server.service.IWeChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import com.tdd.api.server.domain.param.wx.service.TemplateDataVo;
import com.tdd.api.server.domain.param.wx.service.WxMssVo;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author TDD
 * @version V1.0.0
 * @description: ${Description}
 * @date 2020/3/9 14:51
 * @copyright Copyright © 2019
 */
@Service
@Slf4j
public class WeChatServiceImpl implements IWeChatService {

    private final String appId = "wxe3b3eaceb44c3405";

    //c1f13dad1415d6ce34806162a935063f
    private final String appSecret = "c1f13dad1415d6ce34806162a935063f";

    private String accessToken;

    private LocalDateTime tokenTime;

    @Override
    public String getOpenid(String code) {
        String openid = null;
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
                + "&secret=" + appSecret
                + "&js_code=" + code
                + "&grant_type=authorization_code";
        log.info("url >> {}", url);
        //{"session_key":"JhpyFZpng0JMwUQst3VqPQ==","openid":"o4ecR5tX_kHzNElQK6kpirQQIF-A"}
        //{"errcode":40029,"errmsg":"invalid code, rid: 6413bfc7-4c500b19-087eb3cb"}

        String res = HttpUtil.createGet(url).execute().body();
        log.info("res >> {}", res);
        JSONObject json = JSONUtil.parseObj(res);
        if (json.containsKey("openid")) {
            openid = json.getStr("openid");
        }
        return openid;
    }

    private String getAccessToken() {
        if (StrUtil.isEmpty(accessToken) || tokenTime == null || tokenTime.isBefore(LocalDateTime.now())) {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
            String result = HttpUtil.get(url);
            System.out.println("getToken >> result >>" + result);
            JSONObject entries = JSONUtil.parseObj(result);
            accessToken = entries.getStr("access_token");
            tokenTime = LocalDateTime.now().plusMinutes(30);
        }
        log.info("get Token >> {} >> {}",tokenTime,accessToken);
        return accessToken;
    }


    private PushReturn pushMessage(String openid, String page, String templateId, Map<String, TemplateDataVo> data) {
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openid);
        wxMssVo.setPage(page);
        wxMssVo.setTemplate_id(templateId);
        wxMssVo.setData(data);
        String body = JSONUtil.toJsonStr(wxMssVo);
        log.info(" pushMessage >> body >> {} " , body);
        String msg = HttpUtil.post(url, body);
        log.info(" pushMessage >> re >> {}" , msg);
        return JSONUtil.toBean(msg, PushReturn.class);
    }

    /**
     * 审核通知
     */
    @Override
    public PushReturn pushExamineMessage(String openid, String desc, String processName, String submit, String time) {
        //跳转的小程序页面
        String page = "pages/index/index";
        //模板ID
        String templateId = "PZfZc5F8Z1penKbAEjr-sUl1Z3jGBW49Gu_MydVIROU";
        Map<String, TemplateDataVo> data = new HashMap<>();
        //发送内容
        data.put("thing1", new TemplateDataVo(desc));
        //审核项目
        data.put("thing16", new TemplateDataVo(processName));
        //申请人
        data.put("thing14", new TemplateDataVo(submit));
        //申请时间
        data.put("time15", new TemplateDataVo(time));
        return pushMessage(openid, page, templateId, data);
    }


}
